<template>
<div>
  <div class="search">
    <input type="text" v-model="keyword" placeholder="输入城市名或拼音" class="search-input">
  </div>
  <div class="search-content" v-show="keyword">
    <ul>
      <li class="search-item border-bottom"
          v-for="item in list"
          :key="item.id"
          @click="handleCityClick(item.name)"
      >
        {{ item.name }}
      </li>
      <li class="search-item border-bottom" v-show="noData">
        没有找到匹配数据
      </li>
    </ul>
  </div>
</div>
</template>

<script>
import { mapMutations } from 'vuex'
export default {
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  props: {
    cities: Object
  },
  methods: {
    handleCityClick (city) {
      // this.$store.commit('getChange', city) //用了mapMutations 就可以不用那么麻烦了
      // this.$store.dispatch('changeCity', city) //因为这里没有用到异步的操作，所以可以跳过actions直接用mutations
      this.getChange(city)
      this.$router.push('/')
    },
    ...mapMutations(['getChange'])
  },
  computed: {
    noData () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      if (!this.keyword) {
        this.list = []
      }
      const result = []
      for (let i in this.cities) {
        this.cities[i].forEach((value) => {
          if (value.spell.indexOf(this.keyword) > -1 ||
            value.name.indexOf(this.keyword) > -1) {
            result.push(value)
          }
        })
      }
      this.list = result
    }
  }
}
</script>

<style scoped lang="stylus">
  @import '~styles/varibles.styl'
  .search
    padding .1rem;
    margin-top -.1rem;
    background $bgColor
    .search-input
      width 100%
      height .62rem
      line-height .62rem
      text-align center
      box-sizing border-box
      border-radius .06rem
      padding 0 .1rem
      color #666
  .search-content
    overflow hidden
    z-index 1
    position absolute
    top 1.58rem
    right 0
    left 0
    bottom 0
    background #eee
    .search-item
      line-height .62rem
      padding-left .2rem
      background #fff
      color #666
</style>
